﻿using OnlineMealOrdering.Common;
using OnlineMealOrdering.Domain;
using OnlineMealOrdering.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using System.ComponentModel.DataAnnotations;

namespace OnlineMealOrdering.Models
{
    public class LoginModel
    {
        [Display(Name = "登陆账号")]
        [Required(ErrorMessage = "账号是必填项")]
        [StringLength(20, ErrorMessage = "账号不恩能够超过20个字符")]
        public string UserCode { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "登陆密码")]
        [Required(ErrorMessage = "密码是必填项")]
        [StringLength(20, ErrorMessage = "账号不能够超过20个字符")]
        public string Password { get; set; }

        [Display(Name = "验证码")]
        [Required(ErrorMessage = "*")]
        [MinLength(4, ErrorMessage = "验证码长度为4位数")]
        public string ValidateCode { get; set; }

        [Display(Name = "自动登录")]
        public bool AutoLogin { get; set; }

    }

    public class AccountModel : EntityModelBase
    {
        #region properties

        public int? Id { get; set; }

        [Display(Name = "账号：")]
        [Required(ErrorMessage = "账号是必填项")]
        public string UserCode { get; set; }

        [Display(Name = "昵称：")]
        [Required(ErrorMessage = "昵称必填项")]
        public string Name { get; set; }

        [DataType(DataType.Password)]
        [StringLength(20, MinimumLength = 6, ErrorMessage = "密码长度最小6，最大20个字符")]
        [Required(ErrorMessage = "密码是必填项")]
        [Display(Name = "密码：")]
        public string Password { get; set; }

        [Display(Name = "确认密码：")]
        [Required(ErrorMessage = "密码是必填项")]
        //[Compare("Password", ErrorMessage = "密码输入的不一致!")]
        public string ConfirmPassword { get; set; }

        [Display(Name = "密码问题：")]
        [Required(ErrorMessage = "密码问题必填项")]
        public string Question { get; set; }

        [Display(Name = "密码答案：")]
        [Required(ErrorMessage = "密码答案必填项")]
        public string Answer { get; set; }

        [Display(Name = "区域：")]
        public string Area { get; set; }

        [Display(Name = "地址：")]
        public string Address { get; set; }

        [Display(Name = "验证码：")]
        [Required(ErrorMessage = "*")]
        [MaxLength(4, ErrorMessage = "*")]
        public string VCode { get; set; }

        public EnumAccountType AccountType { get; set; }

        //经度
        public decimal Longitude { get; set; }
        //维度
        public decimal Latitude { get; set; }

        public List<string> Roles { get; set; }

        public List<SelectListItem> AllRoles { get; set; }

        #endregion

        #region static methods

        public static AccountModel CreateUser(string userCode, string name, string password, string question, string answer, string area, string address)
        {
            var entity = UserEntity.CreateUser(userCode, name, password, question, answer, area, address, new List<string>() { RolesDefinition.ConsumerRoleCode });
            Ctx.Add<UserEntity>(entity);
            return entity.ToAccountModel();

        }

        public static AccountModel CreateOAuth2User(string name, string access_token, string expires_in, string refresh_token, string openid, string openkey,string faceImage)
        {
            var entity = UserEntity.CreateOAuth2User(name, access_token, expires_in, refresh_token, openid, openkey, new List<string>() { RolesDefinition.ConsumerRoleCode },faceImage);
            Ctx.Add<UserEntity>(entity);
            return entity.ToAccountModel();
        }

        public static bool IsExistsUser(string userCode)
        {
            return Ctx.EntitySet<UserEntity>().Any(a => a.UserCode == userCode);
        }

        public static List<AccountModel> GetAllUser(int page, int rows)
        {
            var query = Ctx.EntitySet<UserEntity>().OrderBy(a => a.Id).Skip((page - 1) * rows).Take(rows).ToList();
            List<AccountModel> list = new List<AccountModel>();
            foreach (var item in query)
            {
                list.Add(item.ToAccountModel());
            }
            return list;
        }

        public static AccountModel GetUser(int userId)
        {
            var user = Ctx.EntitySet<UserEntity>().SingleOrDefault(a => a.Id == userId);
            if (user == null)
                throw new BusinessException(string.Format("用户(id:{0})不存在", userId));

            var model = user.ToAccountModel();

            return model;
        }

        public static AccountModel GetUser(string userCode)
        {
            var user = Ctx.EntitySet<UserEntity>().SingleOrDefault(a => a.UserCode == userCode);
            if (user == null)
                throw new BusinessException(string.Format("用户账号{0}不存在", userCode));

            var model = user.ToAccountModel();

            return model;
        }

        public static void SaveLongitudeLatitude(decimal longitude, decimal latitude)
        {
            var userCode = SiteHelper.CurrentUser.UserCode;
            var user = Ctx.EntitySet<UserEntity>().SingleOrDefault(a => a.UserCode == userCode);
            if (user == null) return;
            user.SaveLongitudeLatitude(longitude, latitude);
            Ctx.SubmitChanges();
        }

        public static bool ValidateUser(string userCode, string password)
        {
            var ctx = Ctx;
            var user = ctx.EntitySet<UserEntity>().SingleOrDefault(a => a.UserCode == userCode && a.AccountType == EnumAccountType.None);
            if (user == null)
                throw new BusinessException(string.Format("登录失败！账号或密码错误。", userCode));

            string encryptedPassword = EncryptHelper.EncryptUserPassword(password);//把yonghukey加密后比对

            return encryptedPassword == user.Password ? true : false;
        }


        public static bool OAuth2ValidateUser(string openid, string openkey)
        {
            var ctx = Ctx;            
            var user = ctx.EntitySet<UserEntity>().SingleOrDefault(a => a.UserCode == openid);
            if (user == null)
                throw new BusinessException(string.Format("登录失败！账号或密码错误。", openid));

            //加密openkey
            string encryptedPassword = new EncryptHelper().Encrypt(openkey);

            return encryptedPassword == user.Password ? true : false;
        }




        public static List<string> GetRolesOfUser(string userCode)
        {
            List<string> roles = new List<string>();

            var ctx = Ctx;
            var user = ctx.EntitySet<UserEntity>().SingleOrDefault(a => a.UserCode == userCode);
            if (user != null && user.Roles != null)
                user.Roles.ToList().ForEach(a => roles.Add(a.RoleCode));

            return roles;
        }



        #endregion

        #region Method

        public List<System.Web.Mvc.SelectListItem> GetQuestion()
        {
            var AllDeliveryType = new List<System.Web.Mvc.SelectListItem>();
            var enums = ParseEnumeration.GetEnumerations(typeof(FindPasswordQuestion));
            foreach (var item in enums)
            {
                AllDeliveryType.Add(new System.Web.Mvc.SelectListItem()
                {
                    Text = item.DisplayName,
                    Value = ((int)item.Value).ToString()
                });
            }
            return AllDeliveryType;
        }
        #endregion
    }

    public class OAuth2AccountModel
    {
        public string OpenID { get; set; }

        public string AccessToken { get; set; }


    }


}
